package com.photoeditor.demo.util;

import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import com.common.base.log.DLog;
import com.photoeditor.BuildConfig;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by Lai on 2018/3/21 0021.
 */

public class FloatWindowPermissionUtil {

    private static final String TAG = "PermissionUtil";

    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
    private static final String XIAOMI = "xiaomi";
    private static final String XIAOMI_UI = "miui";
    private static final String MIUI_V5 = "V5"; // MIUI版本5
    private static final String MIUI_V6 = "V6"; // MIUI版本6
    private static final String MIUI_V7 = "V7"; // MIUI版本7
    private static final String MIUI_V8 = "V8"; // MIUI版本

    private static final String HUAWEI_MANUFACTURER = "HUAWEI";
    private static final String HUAWEI_BRAND = "Huawei";

    private static final String SAMSUNG_MANUFACTURER = "samsung";
    private static final String SAMSUNG_BRAND = "samsung";

    private final static String SONY_T2[] = {"XM50h"};
    private final static String[] HUAWEI_X1 = {"MediaPad X1 7.0"};

    private final static String FLYME_MANUFACTURER = "Meizu";
    private final static String FLYME_BRAND = "Meizu";

    // SDK版本号
    private static final int SDK_INT = Build.VERSION.SDK_INT;

    // 系统定制商
    private static final String BRAND = Build.BRAND;

    private static final String HOST = Build.HOST;

    // ROM制造商
    private static final String MANUFACTURER = Build.MANUFACTURER;

    /**
     * 是否需要申请权限
     *
     * @param context
     * @return
     */
    public static boolean isNeedPermission(Context context) {
        if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return !Settings.canDrawOverlays(context);
            }
            if (isFloatWindowOpAllowed(context)) {
                return false;
            }
        }
        if (isMiUI() && isMIUIV6up()) {
            return true;
        } else if (isMiUI() && isMIUIV5()) {
            if (isPad(context) || SDK_INT >= Build.VERSION_CODES.KITKAT) {
                return true;
            }
            if (!isAppRunningForeground(context)) {
                return true;
            }
        } else if (isHuaWei()) {
            if (!isAppRunningForeground(context)) {
                return true;
            }
        } else if (isFlyme()) {
            return true;
        }
        return false;
    }

    /**
     * 跳转设置权限页面
     * @param context
     */
    public static void requestPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissionAfterM(context);
            return;
        }
        if (isMiUI()) {
            openMiuiPermissionActivity(context);
        } else if (isHuaWei()) {
            openHuaWeiNotificationManager(context);
        } else if (isFlyme()) {
            openAccessSettingForFlyme(context);
        }
    }

    /**
     * 23版本悬浮窗权限申请页面
     */
    private static void requestPermissionAfterM(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    /**
     * 判断悬浮窗权限
     * 19 4.4以下判断不准确
     */
    public static boolean isFloatWindowOpAllowed(Context context) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= Build.VERSION_CODES.KITKAT) {
            return checkOp(context, 24); //24表示悬浮窗权限在AppOpsManager中
        } else {
            //0x8000000表示1000000000000000000000000000如果&第28位所得值为1则该位置被置为1，悬浮窗打开
            return (context.getApplicationInfo().flags & 0x8000000) == 1 << 27;
        }
    }

    protected static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= Build.VERSION_CODES.KITKAT) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService("appops");
            try {
                Object object = invokeMethod(manager, "checkOp", op, Binder.getCallingUid(), getPackageName(context));
                return AppOpsManager.MODE_ALLOWED == (Integer) object;
            } catch (Exception e) {
                DLog.w(TAG, "checkOp: " + e.toString());
            }
        } else {
            DLog.d(TAG, "checkOp: Below API 19 cannot invoke!");
        }
        return false;
    }

    public static String getPackageName(Context context) throws PackageManager.NameNotFoundException {
        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return pInfo.packageName;
    }

    public static Object invokeMethod(AppOpsManager manager, String method, int op, int uid, String packageName) {
        Class c = manager.getClass();
        try {
            Class[] classes = new Class[]{int.class, int.class, String.class};
            Object[] x2 = {op, uid, packageName};
            Method m = c.getDeclaredMethod(method, classes);
            return m.invoke(manager, x2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static boolean isHuaWei() {
        boolean result = false;
        if (BRAND != null && BRAND.equalsIgnoreCase(HUAWEI_BRAND)) {
            result = true;
        }

        return result;
    }

    public static void openHuaWeiNotificationManager(Context context) {
        try {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            localIntent.setClassName("com.huawei.systemmanager", "com.huawei.notificationmanager.ui.NotificationManagmentActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivity(localIntent);
        } catch (ActivityNotFoundException | SecurityException e) {
            // TODO: 提示语
        }
    }

    public static boolean isMiUI() {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && HOST != null && HOST.toLowerCase() != null
                && HOST.toLowerCase().contains(XIAOMI_UI)) {
            result = true;
        }
        return result;
    }

    public static boolean isFlyme() {
        boolean result = false;
        // 针对机器生产商
        if (MANUFACTURER != null && MANUFACTURER.equalsIgnoreCase(FLYME_MANUFACTURER)) {
            result = true;
        }
        if (BRAND != null && BRAND.equalsIgnoreCase(FLYME_BRAND)) {
            result = true;
        }
        return result;
    }

    public static boolean isSamsung() {
        boolean result = false;
        // 针对机器生产商
        if (MANUFACTURER != null && MANUFACTURER.equalsIgnoreCase(SAMSUNG_MANUFACTURER)) {
            result = true;
        }
        if (BRAND != null && BRAND.equalsIgnoreCase(SAMSUNG_BRAND)) {
            result = true;
        }

        return result;
    }

    // 判断当前设备是否为平板
    public static boolean isPad(Context context) {
        // 机型过滤，这些手机并不是平板
        return !(isModel(SONY_T2) || isModel(HUAWEI_X1))
                && (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static boolean isModel(String[] models) {
        final String board = Build.MODEL;
        if (board == null) {
            return false;
        }
        try {
            for (String model : models) {
                if (board.equals(model)
                        || board.equals(model.toLowerCase())
                        || board.equals(model.toUpperCase())) {
                    return true;
                }
            }
        } catch (Exception ignored) {
        }
        return false;
    }

    /**
     * 跳转到设置界面
     * v5跳转到app设置页 v6跳转到app权限管理页
     */
    public static void openMiuiPermissionActivity(Context context) {
        try {
            Intent localIntent = new Intent("emui.intent.action.APP_PERM_EDITOR");
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivity(localIntent);
        } catch (ActivityNotFoundException | SecurityException localActivityNotFoundException) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException | SecurityException e) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void openAccessSettingForFlyme(Context context) {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
            context.startActivity(intent);
        } catch (Exception e) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
            e.printStackTrace();
        }
    }

    /**
     * MIUI 5 在pad上和4.4(19)上没有悬浮窗权限应用内并不会显示气泡, 4.2(17)以下能显示
     * MIUI 6 没有权限无法显示
     */
    public static boolean isMIUIV6up() {
        try {
            final BuildProperties prop = BuildProperties.newInstance();
            String mVersionName = prop.getProperty(KEY_MIUI_VERSION_NAME, null);
            return mVersionName != null && (TextUtils.equals(MIUI_V6, mVersionName) || TextUtils.equals(MIUI_V7, mVersionName) || TextUtils.equals(MIUI_V8, mVersionName));
        } catch (final IOException e) {
            return false;
        }
    }

    /**
     * MIUI 5 在pad上和4.4(19)上没有悬浮窗权限应用内并不会显示气泡, 4.2(17)以下能显示
     * MIUI 6 没有权限无法显示
     */
    public static boolean isMIUIV5() {
        try {
            final BuildProperties prop = BuildProperties.newInstance();
            String mVersionName = prop.getProperty(KEY_MIUI_VERSION_NAME, null);
            return mVersionName != null && TextUtils.equals(MIUI_V5, mVersionName);
        } catch (final IOException e) {
            return false;
        }
    }

    public static boolean isAppRunningForeground(Context var0) {
        ActivityManager var1 = (ActivityManager) var0.getSystemService("activity");
        List var2 = var1.getRunningTasks(1);
        boolean var3 = var0.getPackageName().equalsIgnoreCase(((ActivityManager.RunningTaskInfo) var2.get(0)).baseActivity.getPackageName());
//        EMLog.d("utils", "app running in foregroud：" + var3);
        return var3;
    }
}
